package com.eol.admin.modules.business;

import com.eol.admin.common.utils.SecurityUtils;
import com.eol.common.exception.BaseException;
import com.eol.common.utils.StringUtils;
import com.eol.entity.po.merchant.ZMerchant;
import com.eol.service.merchant.ZMerchantService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: liulinhui
 * Date: 2020/6/5
 * Time: 10:13 PM
 * Description: AdminCommonUtils
 */
@Component
public class AdminCommonUtils {

    @Resource
    private ZMerchantService zMerchantService;

    /**
     * 用户是否为商户
     */
    public boolean isMerchant() {
        return StringUtils.isNotNullOrEmpty(getUserMerchantId());
    }

    /**
     * 查询用户所属的商户ID
     */
    public String getUserMerchantId() {
        Long userId = SecurityUtils.getUserId();
        String merchantId = zMerchantService.selectMerchantIdByUserId(userId);
        if (StringUtils.isNotNullOrEmpty(merchantId)) return merchantId;
        else
            return "";
    }

    public void validateMerchant(String merchantId) {
        if (!isMerchant()) return;
        List<String> merchantList = getSelectMerchant();
        if (null != merchantList && !merchantList.contains(merchantId))
            throw new BaseException("您无权操作");

    }

    /**
     * 用户商户以及下级商户
     */
    public List<String> getSelectMerchant() {
        String merchantId = getUserMerchantId();
        if (StringUtils.isNullOrEmpty(merchantId)) return null;
        Set<String> set = new HashSet<String>() {{
            add(merchantId);
        }};
        List<ZMerchant> zMerchantList = zMerchantService.selectList(ZMerchant.builder()
                .pid(merchantId)
                .build());
        zMerchantList.forEach(zMerchant -> {
            set.add(zMerchant.getId());
        });
        return set.size() > 0 ? new ArrayList<>(set) : null;
    }
}
